import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/common/user_track/user_track.dart';
import 'package:dk_flutter_module_sale/phoenix/api/revision_main_api.dart';
import 'package:dk_flutter_module_sale/phoenix/home/bean/home_chart_bean.dart';
import 'package:dk_flutter_module_sale/phoenix/home/bean/home_contract_bean.dart';
import 'package:dk_flutter_module_sale/phoenix/home/bean/home_form_bean.dart';
import 'package:dk_flutter_module_sale/phoenix/home/bean/home_message_bean.dart';
import 'package:dk_flutter_module_sale/phoenix/home/bean/ui_const_bean.dart';
import 'package:dk_flutter_module_sale/phoenix/home/bean/work_home_bean.dart';
import 'package:dk_flutter_module_sale/phoenix/home/widget/tool_empty_widget.dart';
import 'package:dk_flutter_module_sale/phoenix/home/widget/work_contract_widget.dart';
import 'package:dk_flutter_module_sale/phoenix/home/widget/work_form_widget.dart';
import 'package:dk_flutter_module_sale/phoenix/home/widget/work_information_widget.dart';
import 'package:dk_flutter_module_sale/phoenix/home/widget/work_message_item_widget.dart';
import 'package:dk_flutter_module_sale/phoenix/home/widget/work_muti_chart_widget.dart';
import 'package:dk_flutter_module_sale/phoenix/home/widget/work_sigle_chart_widget.dart';
import 'package:dk_flutter_module_sale/phoenix/home/widget/work_tool_widget.dart';
import 'package:dk_flutter_module_sale/phoenix/home/widget/work_waiting_matter_widget.dart';
import 'package:flutter/material.dart';
import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:sensors_analytics_flutter_plugin/sensors_analytics_flutter_plugin.dart';

class MyWorkPage extends CommonPage {
  @override
  void onInitState(CommonPageBloc pageBloc) {
    pageBloc.dataHttpGet(
      path: RevisionMainApi.homeMyWorkUrl,
      handleResult: (dynamic data) {
        WorkHomeBean homeBean = WorkHomeBean.fromJson(data);
        List<WorkHomeBean> workHomeBeanList = List<WorkHomeBean>();
        if (homeBean != null) {
          workHomeBeanList.add(homeBean);
        }
        pageBloc.switchPage(MyWorkWidget(pageBloc, workHomeBeanList));
      },
      showLoading: false,
      showSuccessMsg: false,
    );
  }
}

class MyWorkWidget extends StatefulWidget {
  final CommonPageBloc pageBloc;
  final List<WorkHomeBean> workHomeBeanList;
  MyWorkWidget(this.pageBloc, this.workHomeBeanList);

  @override
  State<StatefulWidget> createState() =>
      new MyWorkState(pageBloc, workHomeBeanList);
}

class MyWorkState extends State<MyWorkWidget>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  WorkHomeBean workHomeBean;
  HomeFormBean homeFormBean;
  HomeChartBean homeChartBean;
  HomeContractBean homeContractBean;
  HomeMessageBean homeMessageBean;
  CommonPageBloc pageBloc;
  List<WorkHomeBean> workHomeBeanList;
  DkEasyRefreshController easyRefreshController;

  MyWorkState(this.pageBloc, this.workHomeBeanList);

  @override
  void initState() {
    super.initState();
    easyRefreshController = DkEasyRefreshController();
    if (workHomeBeanList != null && workHomeBeanList.length > 0) {
      workHomeBean = workHomeBeanList[0];
    }
    _buildRefreshHome();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      //color: Color(0xff3274F9),
      child: DkRefreshListWidget.custom(
          header: DkClassicalHeader(
            refreshText: "下拉刷新页面",
            refreshReadyText: "松开刷新",
            refreshingText: "刷新中...",
            refreshedText: "刷新完成",
            refreshFailedText: "刷新失败",
            noMoreText: "没有更多数据了",
            infoText: "上次更新 %T",
          ),
          controller: easyRefreshController,
          onRefresh: this.refreshPage,
          emptyWidget: workHomeBeanList.length == 0
              ? LogicPage(PortalConfig.smallEmptyPageParam)
              : null,
          slivers: <Widget>[
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  return _buildHomeView();
                },
                childCount: workHomeBeanList.length,
              ),
            ),
          ]),
    );
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> refreshPage() async {
    this.widget.pageBloc.dataHttpGet(
        showLoading: false,
        path: RevisionMainApi.homeMyWorkUrl,
        handleResult: (dynamic data) {
          setState(() {
            easyRefreshController.finishRefresh(success: true);
            workHomeBean = WorkHomeBean.fromJson(data);
            if (workHomeBean != null) {
              workHomeBeanList.clear();
              workHomeBeanList.add(workHomeBean);
            }
          });
          _buildRefreshHome();
        },
        handleFailResult: (dynamic data1, dynamic data2) {
          easyRefreshController.finishRefresh(success: false);
        },
        handleErrorCode: (dynamic data1) {
          easyRefreshController.finishRefresh(success: false);
        });
  }

  List<Widget> _buildHomeBoxView() {
    List<Widget> results = List<Widget>();
    if (workHomeBean != null) {
      //常用工具
      results.add(DkVisibilityCompose(VisibilityComposeOption.gone(
        (BuildContext context) {
          return WorkToolWidget(
            workHomeBean.commontool,
            () {
              goEditToolsPage();
              UserTrack.track("click_main_more_tools", null);
            },
          );
        },
        visible: (workHomeBean.commontool != null &&
            workHomeBean.commontool.list != null &&
            workHomeBean.commontool.list.length > 0),
      )));
      results.add(DkVisibilityCompose(VisibilityComposeOption.gone(
        (BuildContext context) {
          return ToolEmptyWidget(() {
            goEditToolsPage();
          });
        },
        visible: ((workHomeBean.commontool == null) ||
            (workHomeBean.commontool.list == null &&
                workHomeBean.commontool != null) ||
            (workHomeBean.commontool != null &&
                workHomeBean.commontool.list != null &&
                workHomeBean.commontool.list.length == 0)),
      )));

      //待办事项
      if (workHomeBean.todoModule != null &&
          workHomeBean.todoModule.items != null &&
          workHomeBean.todoModule.items.list != null &&
          workHomeBean.todoModule.items.list.length > 0) {
        results.add(
            _buildWaitingMatterItemList(workHomeBean.todoModule.items.list[0]));
      }
      //二次更新
      for (UpdateModuleListBean module in workHomeBean.updateModule) {
        if (module.moduleType == null) continue;
        if (module.moduleType == 3) {
          results.add(
            WorkFormWidget(module, homeFormBean, (HomeFormBean homeFormBean) {
              (homeChartBean == null)
                  ? refreshFormWarp(module)
                  : RouteUtil.goPage(homeFormBean.appRouteUrl);
            }),
          );
        } else if (module.moduleType == 4) {
          results.add(
            DkVisibilityCompose(VisibilityComposeOption.gone(
              (BuildContext context) {
                return WorkSigleChartWidget(module, homeChartBean,
                    (HomeChartBean homeChartBean) {
                  if (homeChartBean != null) {
                    RouteUtil.goPage(homeChartBean.appRouteUrl);
                  }
                });
              },
              visible:
                  ((homeChartBean != null && homeChartBean.list.length == 1)),
            )),
          );

          results.add(
            DkVisibilityCompose(VisibilityComposeOption.gone(
              (BuildContext context) {
                return WorkMutiChartWidget(module, homeChartBean,
                    (HomeChartBean homeChartBean) {
                  (homeChartBean == null)
                      ? refreshChart(module)
                      : RouteUtil.goPage(homeChartBean.appRouteUrl);
                });
              },
              visible: (objEmpty(homeChartBean)) ||
                  (homeChartBean != null && homeChartBean.list.length >= 2),
            )),
          );
        } else if (module.moduleType == 5) {
          if (homeMessageBean != null) {
            for (int i = 0; i < homeMessageBean.list.length; i++) {
              MessageBean messageBean = homeMessageBean.list[i];
              results.add(_buildMessageItemList(messageBean, module));
            }
          } else {
            results.add(DkVisibilityCompose(VisibilityComposeOption.gone(
              (BuildContext context) {
                return _buildMessageItemList(null, module);
              },
              visible: (objEmpty(homeMessageBean)) ||
                  (homeMessageBean != null && homeMessageBean.list.length == 0),
            )));
          }
        } else if (module.moduleType == 6) {
          results.add(
            WorkContractWidget(module, homeContractBean,
                (HomeContractBean homeContractBean) {
              (homeContractBean == null)
                  ? refreshContract(module)
                  : RouteUtil.goPage(homeContractBean.appRouteUrl);
            }),
          );
        }
      }
      if (workHomeBean.informations != null &&
          workHomeBean.informations.items != null) {
        for (int i = 0; i < workHomeBean.informations.items.length; i++) {
          ItemsListBean itemBean = workHomeBean.informations.items[i];
          results.add(_buildInformationItemList(itemBean));
        }
      }
    }
    return results;
  }

  void _buildRefreshHome() {
    for (UpdateModuleListBean module in workHomeBean.updateModule) {
      if (module.moduleType == null) continue;
      if (module.moduleType == 3) {
        refreshFormWarp(module);
      } else if (module.moduleType == 4) {
        refreshChart(module);
      } else if (module.moduleType == 5) {
        refreshMessageList(module);
      } else if (module.moduleType == 6) {
        refreshContract(module);
      }
    }
  }

  Widget _buildInformationItemList(ItemsListBean itemBean) {
    return WorkInformationWidget(itemBean);
  }

  Widget _buildMessageItemList(
      MessageBean itemBean, UpdateModuleListBean module) {
    return WorkMessageItemWidget(module, itemBean, (value) {
      if (value != null) {
        RouteUtil.goPage(itemBean.appRouteUrl);
      } else {
        refreshMessageList(module);
      }
    });
  }

  Widget _buildWaitingMatterItemList(TodoItem todoItem) {
    return WorkWaitingMatterWidget(workHomeBean.todoModule, todoItem,
        (TodoItem todoItem) {
      Map<String, dynamic> map = Map<String, dynamic>();
      map["name"] = todoItem.departName;
      UserTrack.track("click_main_todo_list", map);
      RouteUtil.goPage(todoItem.appRouteUrl);
    }, (String value) {
      SensorsAnalyticsFlutterPlugin.track("clicktodolist", null);
      RouteUtil.goPage(value);
    });
  }

  void refreshCommonTool() {
    pageBloc.dataHttpGet(
      path: RevisionMainApi.homeMyWorkUrl,
      queryMap: {},
      handleResult: (dynamic data) {
        workHomeBean = WorkHomeBean.fromJson(data);
        setState(() {});
      },
      showLoading: false,
      showSuccessMsg: false,
    );
  }

  void refreshFormWarp(UpdateModuleListBean module) {
    pageBloc.dataHttpGet(
      path: module.hostUrl,
      queryMap: {},
      handleResult: (dynamic data) {
        homeFormBean = HomeFormBean.fromJson(data);
        setState(() {});
      },
      showLoading: false,
      showFailMsg: false,
      showSuccessMsg: false,
    );
  }

  void refreshChart(UpdateModuleListBean module) {
    pageBloc.dataHttpGet(
      path: module.hostUrl,
      queryMap: {},
      handleResult: (dynamic data) {
        homeChartBean = HomeChartBean.fromJson(data);
        setState(() {});
      },
      showLoading: false,
      showFailMsg: false,
      showSuccessMsg: false,
    );
  }

  void refreshMessageList(UpdateModuleListBean module) {
    pageBloc.dataHttpGet(
      path: module.hostUrl,
      queryMap: {},
      handleResult: (dynamic data) {
        homeMessageBean = HomeMessageBean.fromJson(data);
        setState(() {});
      },
      showLoading: false,
      showFailMsg: false,
      showSuccessMsg: false,
    );
  }

  void refreshContract(UpdateModuleListBean module) {
    pageBloc.dataHttpGet(
      path: module.hostUrl,
      queryMap: {},
      handleResult: (dynamic data) {
        homeContractBean = HomeContractBean.fromJson(data);
        setState(() {});
      },
      showLoading: false,
      showFailMsg: false,
      showSuccessMsg: false,
    );
  }

  void goEditToolsPage(){
    RouteUtil.goPage("dkwidget://app/common/EditTools",widgetContext:context,widgetResultCallback:  (Map<String, dynamic> resultMap){
      if( resultMap!=null && resultMap["needRefresh"]) {
        refreshCommonTool();
      }
    });
  }

  Widget _buildHomeView() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: _buildHomeBoxView(),
    );
  }
}
